<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
include 'database.inc';

class model{
		public $id;
		public $fields;
		public $tablename;

function __construct(){
	mysql_connect(DB_SERVER,DB_USER,DB_PASS);
	mysql_select_db(DB_NAME);
	$this->fields = $this->getFieldsList();
}

public function __destruct() {
    mysql_close();
}
    
public function showTableBody(){
    echo "<tbody>";
	$sql = "SELECT * FROM ".$this->tablename;
    $result = mysql_query($sql) or die($sql.":<br>".mysql_error()) ;
	$this->fields = $this->getFieldsList();
	//print_r("<pre>");print_r($this->fields);("</pre>");
	while($row = mysql_fetch_assoc($result)){
		echo "<tr>";
			$last_item = end($this->fields);
			$last_item = each($this->fields);
			//print_r("<pre>"); print_r($val);print_r("</pre>");
				foreach($this->fields as $key => $val){
					if($val == $last_item['value'] && $key == $last_item['key']){

						echo "<td>".$row[$val]."</td>";
						echo "<td><b id=\"modify-button\" value=\"".$row[$this->id]."\">Modify</b></td>";
						echo "<td><b id=\"delete-button\" value=\"".$row[$this->id]."\">Delete</b></td>";
					}
					else{
						echo "<td>".$row[$val]."</td>";
					}
				}
		echo "</tr>";
	}
	mysql_free_result($result);
	$this->showAddForm();
	echo "</tbody>";
}

public function getFieldsList(){
		mysql_connect(DB_SERVER,DB_USER,DB_PASS);
		mysql_select_db(DB_NAME);
	    $sql = "SELECT * FROM ".$this->tablename;
	    $result = mysql_query($sql) or die($sql.":<br>".mysql_error()) ;
	   	$fields = array();
		for ($i = 0; $i < mysql_num_fields($result); ++$i) {
			//$table = mysql_field_table($result, $i); //source table of field
			$field = mysql_field_name($result, $i);
			array_push($fields,$field); 	
		}
		return $fields;
}
	
public function showAddForm(){
	foreach($this->fields as $key => $val){
		echo "<td><input type=\"text\" name=\"".$val."\" class=\"text ui-widget-content ui-corner-all\"></td>";
	}
	echo "<td colspan=\"2\"><center><button id=\"add-button\">Add</button></center></td>"; 
}

public function showDataGrid(){
	echo "<center><div class=\"datagrid\"><table id=\"table_grid\">";
	$this->showTableHead();
	$this->showTableBody();
	echo "</table></div></center>";
}

public function showTableHead(){
    echo "<thead>";
    $this->fields = $this->getFieldsList();
    echo "<tr>";
    	foreach($this->fields as $key => $val){
    		echo "<th>".$val."</th>";
    	}
    	echo "<th>Modify</th>";
    	echo "<th>Delete</th>";
    echo "</tr>";
    echo "</thead>";    	
}
public function showDeleteDialoge(){
	echo "<div id=\"dialog-confirm\" title=\"Delete ?\" style=\"display: none;\">";
	echo "<p><span class=\"ui-icon ui-icon-alert\" style=\"float:left; margin:0 7px 20px 0;\"></span>These item will be deleted and cannot be recovered. Are you sure?</p>";
	echo "</div>";
}
public function showEditForm(){
	echo "<div id=\"dialog-form\" title=\"Edit\" style=\"display: none;\">";
	echo "<p class=\"validateTips\">All form fields are required.</p>";
	
	$this->fields = $this->getFieldsList();
	echo "<form>";
	echo "<fieldset>";
    	foreach($this->fields as $key => $val){
    		echo "<label for=\"name\">".$val."</label>";
    		echo "<input type=\"text\" id=\"name\" name=\"".$val."_edit\" class=\"text ui-widget-content ui-corner-all\" value=\"-\"/>";
    	}
    echo "</fieldset>";
    echo "</form>";
    echo "</div>";
}
public function delete($id){
	mysql_connect(DB_SERVER,DB_USER,DB_PASS);
	mysql_select_db(DB_NAME);
	$sql = "DELETE FROM ".$this->tablename." WHERE ".$this->id." = ".$id;
	$result = mysql_query($sql) or die($sql.":<br>".mysql_error()) ;
}
public function insert($data){
		$glue = ',';
		$fields_string = implode($glue,$this->getFieldsList());
		$glue = '\',\'';
		$data_string = implode($glue,$data);

	$sql = <<<SQL
	INSERT INTO $this->tablename
	($fields_string)
	VALUES('$data_string')
SQL;

	echo "<h1>$sql</h1>";
	$result = mysql_query($sql) or die($sql.":<br>".mysql_error()) ;
	print_r($result);
}	
public function edit($data){
	mysql_connect(DB_SERVER,DB_USER,DB_PASS);
	mysql_select_db(DB_NAME);
	
	print_r("<pre>");print_r($this->getFieldsList());print_r("</pre>");
	$fields = $this->getFieldsList();
	$strings_array = array();
	foreach ($fields as $key => $value) {
    	array_push($strings_array,$fields[$key]." = '".$data[$key]."'");
	}
	$data_string = implode(',',$strings_array);
	
	$sql = <<<SQL
		UPDATE $this->tablename 
		SET
			$data_string
		WHERE $this->id = $data[0];
SQL;

	echo "<h1>$sql</h1>";
	$result = mysql_query($sql) or die($sql.":<br>".mysql_error()) ;
	print_r($result);		
}
public function getHeader(){
		$data = <<<DATA
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Data Grid</title>
		<link rel="stylesheet" type="text/css" href="../css/style-dock-menu.css" />
		<link rel="stylesheet" type="text/css" href="../css/style.css" />
		<link rel="stylesheet" href="../css/jquery.ui.all.css">
		<style>
		</style>
		
		<script src="../js/jquery-1.7.2.js"></script>
		
		<script src="../js/interface.js"></script>
		<script src="../js/ui/jquery.ui.core.js"></script>
		<script src="../js/ui/jquery.ui.widget.js"></script>
		<script src="../js/ui/jquery.ui.mouse.js"></script>
		<script src="../js/ui/jquery.ui.button.js"></script>
		<script src="../js/ui/jquery.ui.draggable.js"></script>
		<script src="../js/ui/jquery.ui.position.js"></script>
		<script src="../js/ui/jquery.ui.resizable.js"></script>
		<script src="../js/ui/jquery.ui.dialog.js"></script>
		<script src="../js/ui/jquery.effects.core.js"></script>
DATA;
		echo $data;
}
public function getHorizontalMenu(){
?>
		<div class="dock" id="dock">
		<div class="dock-container">
		  <a class="dock-item" href="#"><img src="../images/home.png" alt="home" /><span>القائمة</span></a> 
		</div>
		</div>
		<script type="text/javascript">
			$(document).ready(
				function()
				{
					$('#dock').Fisheye(
						{
							maxWidth: 50,
							items: 'a',
							itemsText: 'span',
							container: '.dock-container',
							itemWidth: 40,
							proximity: 90,
							halign : 'center'
						}
					)
				}
			);
$(function() {
$("table tr").hover(
	function(){
		//$(this).find("#actionMenu").fadeIn(200);
		$(this).find("b").css({"visibility":"visible"});
		},
	function(){
			//$(this).find("#actionMenu").fadeOut(200);
		$(this).find("b").css({"visibility":"hidden"});
	}	
);
$('b[id="modify-button"]').click(function() {edit($(this));});
$('b[id="delete-button"]').click(function(){confirm_delete($(this).attr('value'));});
$('button[id="add-button"]').button().click(function(){add();});

function confirm_delete(_id){
	$("#dialog-confirm").dialog({
		resizable: false,
		height:140,
		modal: true,
		buttons: {
			"Yes" : function() {
				$.ajax({
					url: "sql.php",
					type: "POST",
					data: {id : _id,"operation" : "delete","tablename" : "<?php echo $this->tablename; ?>" },
					success: function(data){
						//location.reload();
					}
				});
				$( this ).dialog( "close" );
			},
			"No" : function() {
				$( this ).dialog( "close" );
			}
		}
	});
}
});

function edit(_id){
	var data  = ["<?php echo implode('","',$this->getFieldsList());?>"];
	//$(_id).parent().parent().css('background-color', '#FFA9BD');    	
		$("#dialog-form").dialog({
			height: 300,
			width: 350,
			modal: true,
			buttons: {
				"Edit" : function() {
					var tab = [];
					$.each(data, function(key, val) {
						tab.push(val+"="+$("input[name="+val+"_edit]").val()); 
					});
					var str = tab.join("&");
					//alert(str);
					str += "&operation=edit&tablename=<?php echo $this->tablename; ?>";
						$.ajax({
							url:"sql.php",
							type : "POST",
							data : str,
							success: function(data){
								//location.reload();
							}
						});
					$( this ).dialog("close");
				},
				"Cancel" : function() {$( this ).dialog("close");}
			},
				close: function() {/*TO DO*/}
	});
	$.each(data, function(key, val) {
         	$("input[name="+val+"_edit]").val($(_id).parent().parent().children('td:eq('+key+')').text());

    });    
}

function add(){	
	var data = ["<?php echo implode('","',$this->getFieldsList());?>"];
	var tab = [];
	$.each(data, function(key, val) {
		tab.push(val+"="+$("input[name="+val+"]").val()); 
	});
	
	var str = tab.join("&");
	//alert(str);
	str += "&operation=add&tablename=<?php echo $this->tablename; ?>";
	$.ajax({
		url:"sql.php",
		type : "POST",
		data : str,
		success: function(data){
			//location.reload();
		}
	});
}
</script>
<?php
}
public function getFooter(){
		echo "<center><a href=\"../index\">Home</a></center>";		
	}
}